<?php

namespace Common\Service;

class WechatService {

  private static $instance;
  var $reply_status = array(
    0 => '禁用',
    1 => '启用',
  );
  var $reply_type = array(
    'text' => '文本',
    'news' => '图文',
    'sub' => '关注回复',
    'default' => '默认回复',
  );

  public static function instance() {
    if (self::$instance == null) {
      $instance = new WechatService();
    }
    return $instance;
  }

  function get_autoreply_default_row() {
    return array(
      'type' => 'text',
      'keyword' => '',
      'title' => '',
      'desc' => '',
      'icon' => '',
      'url' => '',
      'url_with_openid' => 0,
      'status' => 1,
    );
  }

  function get_reply_by_cond($config) {
    $default = array(
      'page' => 0,
      'page_size' => C('page_size'),
      'keywords' => '',
      'type' => '',
      'status' => '-1',
      'sort' => 'id',
      'order' => 'DESC',
      'count' => FALSE,
    );

    $config = extend($config, $default);

    $where = array();
    if (!empty($config['type'])) {
      $where['type'] = $config['type'];
    }

    if ($config['status'] >= 0) {
      $where['status'] = $config['status'];
    }

    if (!empty($config['keywords'])) {
      $k = $config['keywords'];
      $where['_string'] = " keyword = '$k' or title like '%$k%' or desc like '%$k%'";
    }

    $Wxautoreply = M('WxAutoreply');
    if ($config['count']) {
      return $Wxautoreply->where($where)->count();
    }

    $limit = '';
    if ($config['page'] > 0) {
      $limit = ($config['page'] - 1 ) * $config['page_size'] . ',' . $config['page_size'];
    }
    $order = $config['sort'] . ' ' . $config['order'];

    $data = $Wxautoreply->where($where)->limit($limit)->order($order)->select();

    return $data ? $data : array();
  }

  function create_reply($data) {
    $Wxautoreply = M('WxAutoreply');
    $ret = $Wxautoreply->add($data);

    if ($ret) {
      return ajax_arr('添加成功', TRUE, array(
        'id' => $ret
      ));
    } else {
      return ajax_arr('添加失败', FALSE);
    }
  }

  function update_reply($id, $data) {
    $Wxautoreply = M('WxAutoreply');
    $ret = $Wxautoreply->where('id = %d', $id)->save($data);

    if ($ret) {
      return ajax_arr('编辑成功', TRUE);
    } else {
      return ajax_arr('编辑失败', FALSE);
    }
  }

  function delete_reply($ids) {
    $Wxautoreply = M('WxAutoreply');

    $ret = $Wxautoreply->delete($ids);
    if ($ret == 0) {
      return ajax_arr('未删除任何数据', FALSE);
    } else if (!$ret) {
      return ajax_arr('删除失败', FALSE);
    } else {
      return ajax_arr('成功删除 ' . $ret . ' 行数据', TRUE);
    }
  }

  function get_reply_by_keyword($keyword) {
    $Wxautoreply = M('WxAutoreply');
    $data = $Wxautoreply->where('keyword="%s"', $keyword)->find();
    return $data ? $data : array();
  }

  function get_reply_by_type($type) {
    $Wxautoreply = M('WxAutoreply');
    $data = $Wxautoreply->where('type="%s"', $type)->select();
    return $data ? $data : array();
  }

}
